<template>
  <div>
    <a-button type="primary" @click="showModal">Open Modal</a-button>
    <a-modal v-model:open="open" title="新建标签" @ok="handleOk" footer>
      <input type="text" placeholder="请输入标签" v-model="tallyText"><button @click="handleCreate">新建</button>
    </a-modal>
  </div>
  <el-table :data="filterTableData" style="width: 100%">
    <el-table-column label="ID" prop="id" />
    <el-table-column label="Tag" prop="name" />
    <el-table-column align="right">
      <template #header>
        <el-input v-model="search" size="small" placeholder="请输入标签查找"></el-input>
      </template>
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.$index, scope.row)">
          Edit
        </el-button>
        <el-button
          size="small"
          type="danger"
          @click="handleDelete(scope.$index, scope.row)"
        >
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>
</template>

<script lang="ts" setup>
import { computed, onMounted, ref } from 'vue'
import {useTagCenter} from '@/stores/tagCenter'
import { ta } from 'element-plus/es/locales.mjs';
import {useEntryStore} from '@/stores/entry'
const TagCenter=useTagCenter();
const entryStore=useEntryStore()
interface User {
  id:number,
  name: string
}
const open = ref<boolean>(false);
let search = ref('')
let tallyText=ref('')
const tableData = ref<User[]>([])
async function getTag(){
  const response= await TagCenter.getTags();
  tableData.value=response.data.data;
  TagCenter.tableData.push(response.data.data)
}
getTag()
async function handleCreate(){
   if(tallyText.value!==''){
    await TagCenter.createTags(entryStore.token,tallyText.value)
    let max=0;
    for(let i=0;i<tableData.value.length;i++){
      if(max<tableData.value[i].id)max=tableData.value[i].id
    }
    tableData.value.push({id:max+1,name:tallyText.value})
    TagCenter.tableData.push({id:max+1,name:tallyText.value})
  }
  tallyText.value = '';
  open.value=false;
}
const filterTableData = computed(() =>
  tableData.value.filter(
    (data) =>
      !search.value ||
      data.name.toLowerCase().includes(search.value.toLowerCase())
  )
)

const handleEdit = (index: number, row: User) => {
  console.log(index, row)
}

async function handleDelete (index: number, row: User) {
  tableData.value.splice(index, 1)
  const tagId = row.id;
  TagCenter.tableData.splice(index,1)
  await TagCenter.deleteTags(entryStore.token ,tagId); 
}
const showModal = () => {
  open.value = true;
};

const handleOk = (e: MouseEvent) => {
  open.value = false;
};
</script>
